package jp.team.nature.reizoukoapp;

import java.util.ArrayList;
import java.util.List;

import jp.team.nature.reizoukoapp.adapter.ReizoukoItemAdapter;
import jp.team.nature.reizoukoapp.constant.Constant;
import jp.team.nature.reizoukoapp.db.ReizoukoItem;
import jp.team.nature.reizoukoapp.db.SQLOpenHelper;
import jp.team.nature.reizoukoapp.dialog.CustomDialogFragment;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;

public class ZaikoKakuninActivity extends ListActivity
	implements OnClickListener, OnItemClickListener {

    private ReizoukoItemAdapter adapter;
    private String retVal;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kakunin);

        showListView();
    }

    private void showListView() {
    	Spinner filter = (Spinner) findViewById(R.id.filter);
    	Spinner sort = (Spinner) findViewById(R.id.sort);

    	// 条件句生成
    	String orderby = "expdate asc";
    	if (sort.getSelectedItem().toString().equals("賞味期限昇順")) {
    		orderby = "expdate asc";
    	} else if (sort.getSelectedItem().toString().equals("賞味期限降順")) {
    		orderby = "expdate desc";
    	}
    	String selection = null;
    	String[] selectionArgs = null;
    	if (filter.getSelectedItem().toString().equals("肉")) {
    		selection = "category = ?"; selectionArgs = new String[] { "肉" };
    	} else if (filter.getSelectedItem().toString().equals("野菜")) {
    		selection = "category = ?"; selectionArgs = new String[] { "野菜" };
    	} else if (filter.getSelectedItem().toString().equals("魚介類")) {
    		selection = "category = ?"; selectionArgs = new String[] { "魚介類" };
    	} else if (filter.getSelectedItem().toString().equals("乳製品")) {
    		selection = "category = ?"; selectionArgs = new String[] { "乳製品" };
    	} else if (filter.getSelectedItem().toString().equals("卵")) {
    		selection = "category = ?"; selectionArgs = new String[] { "卵" };
    	} else if (filter.getSelectedItem().toString().equals("きのこ")) {
    		selection = "category = ?"; selectionArgs = new String[] { "きのこ" };
    	} else if (filter.getSelectedItem().toString().equals("果物")) {
    		selection = "category = ?"; selectionArgs = new String[] { "果物" };
    	} else if (filter.getSelectedItem().toString().equals("麺類")) {
    		selection = "category = ?"; selectionArgs = new String[] { "麺類" };
    	} else if (filter.getSelectedItem().toString().equals("その他")) {
    		selection = "category not in (?, ?, ?, ?, ?, ?, ?, ?)";
    		selectionArgs = Constant.CATEGORIES;
    	}

    	// DB接続
        SQLOpenHelper helper = new SQLOpenHelper(this);
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor c = db.query("zaiko_table",
        		new String[] { "id", "category", "name", "quantity", "buydate", "expdate", "unit" },
                selection, selectionArgs, null, null, orderby);

        List<ReizoukoItem> itemList = new ArrayList<ReizoukoItem>();
        ReizoukoItem title = new ReizoukoItem(); title.setEnabled(false);;
        itemList.add(title);
        boolean isEof = c.moveToFirst();
        while (isEof) {
            ReizoukoItem item = new ReizoukoItem();
            item.setId(c.getInt(0));
            item.setCategory(c.getString(1));
            item.setName(c.getString(2));
            item.setQuantity(c.getFloat(3));
            item.setBuyDate(c.getString(4));
            item.setExpDate(c.getString(5));
            item.setUnit(c.getString(6));
            item.setEnabled(true);

            itemList.add(item);
        	isEof = c.moveToNext();
        }
        c.close();
        db.close();

        // ListView作成
        adapter = new ReizoukoItemAdapter(getApplicationContext(), itemList);
        setListAdapter(adapter);

        // 戻るボタン
    	Button backButton = (Button) findViewById(R.id.button_back);
    	Button filterButton = (Button) findViewById(R.id.siborikomiText);
    	Button sortButton = (Button) findViewById(R.id.narabikaeText);

    	filterButton.setOnClickListener(this);
    	sortButton.setOnClickListener(this);
    	backButton.setOnClickListener(this);

    	// onItemClickListner用意
    	ListView listView = getListView();
    	listView.setOnItemClickListener(this);
    }

    @Override
	public void onClick(View v) {
		if (v == findViewById(R.id.button_back)) {
			finish();
		} else if (v == findViewById(R.id.siborikomiText)) {
			showListView();
		} else if (v == findViewById(R.id.narabikaeText)) {
			showListView();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// ダイアログ生成
		CustomDialogFragment cdf = new CustomDialogFragment();
		cdf.setSelectedItem(adapter.getItem(position));
	    cdf.show(getFragmentManager(), "dialog");
	}

	public void onReturnValue(String value, ReizoukoItem item) {
		retVal = value;

		if (retVal.equals("cancel")) {
			// NOP: キャンセルされたので何もしない
		} else if (retVal.equals("all")) {
			// 全量が選択
	        // DB接続
	        SQLOpenHelper helper = new SQLOpenHelper(this);
	        SQLiteDatabase db = helper.getReadableDatabase();
	        db.delete("zaiko_table", "id= " + item.getId(), null);
	        db.close();
	        (adapter).notifyDataSetChanged();
	        showListView();
		} else {
			// 数量を入力
			Float quantity = Float.valueOf(retVal);
	        SQLOpenHelper helper = new SQLOpenHelper(this);
	        SQLiteDatabase db = helper.getReadableDatabase();
	        if (item.getQuantity() == null || item.getQuantity() <= quantity) {
		        db.delete("zaiko_table", "id= " + item.getId(), null);
	        } else {
		        ContentValues cv = new ContentValues();
		        cv.put("category", item.getCategory());
		        cv.put("name", item.getName());
		        cv.put("quantity", item.getQuantity() - quantity);
		        cv.put("buydate", item.getBuyDate());
		        cv.put("expdate", item.getExpDate());
		        cv.put("unit", item.getUnit());
		        db.update("zaiko_table", cv, "id= " + item.getId(), null);
	        }
	        db.close();
	        (adapter).notifyDataSetChanged();
	        showListView();
		}
	}
}
